package com.ruoyi.system.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.poi.excel.cell.CellUtil;
import com.ruoyi.system.constant.Constants;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringToExcel {

    public static void outputexcel(Map<String,Double> map,String output){
        try {
            FileInputStream inputStream = new FileInputStream(Constants.BASE_DIR+"scale.xlsx");
            //FileInputStream inputStream = new FileInputStream("D:\\png\\images\\scale.xlsx");
            Workbook workbook = new XSSFWorkbook(inputStream);
            CellStyle yellowCellStyle = workbook.createCellStyle();
            yellowCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            yellowCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            for (Map.Entry<String,Double> entry : map.entrySet()) {
                String questionNumber = entry.getKey();
                Double extractedContent = entry.getValue();
                Sheet sheet = workbook.getSheet("Sheet1"); // 请替换为你的工作表名称
                for (int rowindex=1;rowindex<=76;rowindex = rowindex+2){
                    Row row = sheet.getRow(rowindex); // 假设列名在第一行
                    int columnIndex = -1;
                    for (int colindex = 0; colindex <= 18; colindex++) {
                        Cell cell=row.getCell(colindex);
                        try {
                            if (cell.getStringCellValue().equals(questionNumber)) {
                                columnIndex = cell.getColumnIndex();
                                break;
                            }
                        } catch (NullPointerException e) {
                            // ...
                        }
                    }
                    if (columnIndex != -1) {
                        CellStyle cellStyle = sheet.getRow(rowindex+1).getCell(columnIndex).getCellStyle();
                        CellUtil.setCellValue(sheet.getRow(rowindex + 1).createCell(columnIndex), extractedContent,cellStyle);
                    } else {
                        //System.out.println("未找到匹配的列名");
                    }
                }
            }
            // 将工作簿保存回文件
            try (FileOutputStream outputStream = new FileOutputStream(output)) {
                workbook.write(outputStream);
                System.out.println("Excel file updated successfully.");
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
